<template>
	<view class="content">
		<view class="title">
			<!-- <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="onGotUserInfo">获取用户信息</button>
			{{vuex_userinfo.nickName}}
			{{vuex_openid}} -->
		</view>


		<u-sticky>

			<view class="louis-bg-f louis-p-1p">
				<view class="louis-25rpx form ">
					<view class="form-item louis-space-between">
						<view class="louis-flex inputbox">
							<text class="labeltext">商品名称:</text>
							<input class="inputstyle" v-model="from.product" type="text" value="" />
						</view>

						<!-- 	<u-number-box
						 v-model="from.count" color="#fff" bg-color="#409eff"></u-number-box> -->


						<view style="padding-left:10rpx" class="u-number-box louis-space-between">
							<u-icon @tap="circle" class="topre" name="minus-circle" color="#2979ff" size="40"></u-icon>

							<input type="number" @focus="from.count=''" @input="numbercount" @blur="numbercount" style="color:2979ff;30rpx;text-align: center;"
							 v-model="from.count" />

							<u-icon @tap="addnumber" class="topre" name="plus-circle" color="#2979ff" size="40"></u-icon>
						</view>


					</view>
				</view>
				<view class="louis-25rpx form">
					<view class="form-item louis-space-between">
						<view class="louis-flex inputbox">
							<text class="labeltext">商品单价:</text>
							<input class="inputstyle" v-model="from.price" type="number" value="" />
						</view>
						<view style="width: 215rpx;" class="moneybox louis-flex inputbox louis-color-w louis-space-between">
							<text class=" louis-icon-tuipiao louis-40rpx"> </text>
							<text class="money"> {{from.price*from.count}}</text>

						</view>

					</view>
				</view>

				<view v-if="list.length>0" class="louis-28rpx">
					<view style="padding: 10rpx 5rpx 10rpx 5rpx;" class="">
						<view class="louis-space-between">
							<view class="louis-font-right louis-color-P">
								总数量：{{count}}
							</view>
							<view class="louis-font-right louis-color-D">
								总价：¥{{total}}
							</view>
						</view>
						<!-- <view style="padding-top:10rpx;" class="louis-end">
							<view class="ddbutton">
								生成订单
							</view>
						</view> -->
					</view>
					<u-line border-style="solid"></u-line>
				</view>

				<view class="louis-space-around louis-m-1p">
					<u-button type="primary" size="mini" @click="add">录入</u-button>
					<u-button type="warning" size="mini" @click="reset">重置</u-button>
					<u-button type="error" size="mini" @click="deleteall">清空</u-button>
					<u-button type="primary" size="mini" @click="get()">刷新</u-button>
					<u-button type="success" v-if="list.length>0" @click="showsaveform=true" size="mini">保存</u-button>
					<u-button type="success" v-else disabled size="mini">保存</u-button>
				</view>

			</view>
			<u-line border-style="solid"></u-line>
		</u-sticky>







		<view v-if="list.length>0" class="table">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y">
				<u-swipe-action :show="item.show" :index="index" v-for="(item, index) in list" :key="item.id" @click="click" @open="open"
				 :options="options">
					<view class="table-item louis-slide-bottom-1">
						<view @tap="itemshowdetails(index)" class="itemhear  louis-space-between">
							<view class="louis-color-333">
								{{item.product}}
							</view>
							<view class="louis-end ">
								x{{item.count}}
								<text v-if="item.showdetails" class="louis-icon-right iconbottom icon"> </text><text v-else class="louis-icon-right icon">
								</text>
							</view>
						</view>
						<!-- 	<transition name="slide-fade"> -->
						<view v-if="item.showdetails" class="louis-slide-bottom-1">
							<u-line border-style="dashed"></u-line>
							<view class="louis-space-between  showdetails ">
								<text class="louis-color-W">

									单价:{{item.price}}</text>
								<text class="louis-color-D">总价:¥{{item.total}}</text>
							</view>
						</view>
						<!-- </transition> -->

					</view>
				</u-swipe-action>
			</scroll-view>
			<!-- <view style="padding: 60rpx;" class="">

			</view> -->




		</view>
		<louis-view v-else h="800rpx" class="louis-mind-center">
			<u-empty text="订单为空" mode="order"></u-empty>
		</louis-view>
		<u-toast ref="uToast" />
		<u-modal :show-title="false" @confirm="saveorderlist" :show-cancel-button="true" v-model="showsaveform">
			<view class="slot-content">
				<view style="padding:30rpx 40rpx 20rpx 40rpx;font-size: 28rpx;" class="louis-flex">
					<text style="width: 150rpx;" class="labeltext">订单名称:</text>
					<input v-model="fromname" type="text" value="" placeholder="请输入订单名称" />
				</view>
				<u-line border-style="solid"></u-line>
			</view>

		</u-modal>


		<u-modal  v-model="showsaveorderlist" :show-title="false" content="恭喜你,添加成功!" confirm-text="查看详情" cancel-text="下次再看,继续添加">
		</u-modal>

		<u-modal 
		@cancel="get()"
		@confirm="update"
		v-model="showedit" :show-cancel-button="true" :show-title="false">
			<view style="padding: 10rpx 20rpx;" class="louis-25rpx slot-content form">
				<view style="border: 0px;" class="form-item ">
					<view class="louis-flex inputbox">
						<text style="width: 200rpx;" class="labeltext">商品名称:</text>
						<input class="inputstyle" v-model="editem.product" type="text" value="" />
					</view>
					<u-line border-style="solid"></u-line>
					<view class="louis-space-between inputbox">
						<text style="width: 200rpx;" class="labeltext">商品单价:</text>
						<input class="inputstyle" v-model="editem.price" type="number" value="" />
					</view>
					<u-line border-style="solid"></u-line>
					<view class="louis-space-between inputbox">
						<text style="width: 200rpx;" class="labeltext">商品数量:</text>
						
						
						<input class="inputstyle" v-model="editem.count" type="number" value="" />	
						
						
					</view>
					<view class="moneybox  inputbox louis-color-w louis-space-between">
						<text class="labeltext">商品总价:</text>
						<text class="money"> {{editem.price*editem.count}}</text>
					</view>
					<u-line border-style="solid"></u-line>
				</view>
			</view>
		</u-modal>


	</view>
</template>

<script>
	export default {
		data() {
			return {
				showedit: false,
				showsaveorderlist: false,
				orderid: "",
				showsaveform: false,
				fromname: "",
				appid: "wx11661ad67d87437e",
				secret: "51f1e79e8783db55cc2ce801f9599fae",
				scrollTop: 0,
				count: 0,
				total: 0,
				from: {
					product: "", //商品名称
					count: 0, //商品数量
					price: "", //商品单价
					total: "", //商品总价
					show: false,
					showdetails: false,
					openid: "",
				},
				options: [{
						text: '编辑',
						style: {
							fontSize: "25rpx",
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							fontSize: "25rpx",
							backgroundColor: '#dd524d'
						}
					}
				],
				list: [],
				infodata: {},
				editem: {

				}
			}
		},
		mounted() {
			this.get()
			this.checkSession()
			this.getopenid()
		},

		methods: {
			saveorderlist() {

				if (this.fromname == '') {
					this.$refs.uToast.show({
						title: '请输入订单名',
						type: 'error'
					})
					return
				}


				uni.showLoading({
					title: '处理中...'
				})
				uniCloud.callFunction({
					name: 'saveorderlist',
					data: {
						openid: this.$store.state.vuex_openid,
						list: this.list,
						fromname: this.fromname,
						expires_in: Date.now(),
						expires_name: this.$store.state.vuex_userinfo.nickName,
						type: 1, //type=1代表录入
						count: this.count, //总数
						total: this.total, //总金额
						show: false,
						showdetails: false,
					}
				}).then((res) => {
					uni.hideLoading()
					this.fromname = ''


					this.orderid = res.result.id

					this.showsaveorderlist = true


				}).catch((err) => {
					uni.hideLoading()

				})
			},
			onGotUserInfo(e) {
				// 获取用户信息
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log(res);

						const self = this;
						var appid = self.appid; //这里是我的appid，需要改成你自己的
						var secret = self.secret; //密钥也要改成你自己的
						var openid = '';
						var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' +
							res.code + '&grant_type=authorization_code';
						uni.request({
							url: url,
							data: {},
							method: 'GET',
							success: (resrequest) => {
								var obj = {};
								obj.openid = resrequest.data.openid;
								console.log('openid: ' + resrequest.data.openid);
								self.$u.vuex('vuex_openid', resrequest.data.openid)
								obj.expires_in = Date.now() + resrequest.data.expires_in;


								// 获取用户信息

								uni.getUserInfo({
									provider: 'weixin',
									success: (infoRes) => {
										console.log(infoRes);
										this.$u.vuex('vuex_userinfo', infoRes.userInfo);
										let userobj = {}
										userobj.openid = obj.openid
										userobj.expires_in = obj.expires_in
										userobj.userinfo = infoRes.userInfo
										console.log(userobj)
										uniCloud.callFunction({
											name: 'adduser',
											data: userobj
										}).then((res) => {
											console.log(res)
										}).catch((err) => {})
									},
								});




							}
						});



						uni.reLaunch({
							url: '../index/index'
						});
					}
				});
			},
			getopenid() {
				this.from.openid = this.$store.state.vuex_openid
			},
			checkSession() {
				uni.checkSession({
					success() {
						//                 console.log('checkSession success')  
						//                 console.log(arguments)  
					},
					fail() {
						uni.reLaunch({
							url: '../loginwx/loginwx'
						});
					}

				})
			},
			itemshowdetails(index) {
				this.list[index].showdetails = !this.list[index].showdetails
			},
			addnumber() {
				if (this.from.count > 9998) {
					this.$refs.uToast.show({
						title: '最大数量为9999',
						type: 'warning',
					})
					this.from.count = '9999'
					return
				} else {
					this.from.count += 1
				}
			},
			numbercount() {
				if (this.from.count > 9998) {
					this.$refs.uToast.show({
						title: '最大数量为9999',
						type: 'warning',
					})
					this.from.count = 9999
				} else {
					this.from.count *= 1
				}
			},
			circle() {
				if (this.from.count <= 0) {

				} else {
					this.from.count -= 1
				}
			},
			click(index, index1) {
				if (index1 == 1) {
						this.list[index].show=false
					this.remove(this.list[index])

				} else {
						this.list[index].show=false
					this.editem = this.list[index]
					this.showedit = true
					// this.update(this.list[index])
				}
			
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.list[index].show = true;
				this.list.map((val, idx) => {
					if (index != idx) this.list[idx].show = false;
				})
			},
			reset() {
				this.from.product = "", //商品名称
					this.from.count = 0, //商品数量
					this.from.price = "", //商品单价
					this.from.total = "" //商品总价

			},
			deleteall() {
				uniCloud.callFunction({
					name: 'removeall',
					data: {
						openid: this.$store.state.vuex_openid
					},
				}).then((res) => {
					uni.hideLoading()
					this.get()
				}).catch((err) => {
					uni.hideLoading()
				})
			},
			add() {
				this.getopenid()

				if (this.from.count > 9998) {
					this.from.count = 9999
					this.$refs.uToast.show({
						title: '最大数量为9999',
						type: 'warning',
					})

					return
				}

				this.from.total = this.from.price * this.from.count
				if (this.from.product == "") {
					this.$refs.uToast.show({
						title: '请输入商品名称',
						type: 'warning',
					})
					return
				} else if (this.from.price <= 0 || this.from.price == '') {
					this.$refs.uToast.show({
						title: '请输入单价',
						type: 'warning',
					})
					return
				} else if (this.from.count <= 0) {
					this.$refs.uToast.show({
						title: '请输入数量',
						type: 'warning',
					})
					return
				}


				uni.showLoading({
					title: '处理中...'
				})
				uniCloud.callFunction({
					name: 'add',
					data: this.from
				}).then((res) => {
					uni.hideLoading()
					this.get()
				}).catch((err) => {
					uni.hideLoading()

				})
			},
			remove(item) {

				uni.showLoading({
					title: '处理中...'
				})
				uniCloud.callFunction({
					name: 'remove',
					data: {
						id: item._id
					}
				}).then((res) => {
					uni.hideLoading()
					this.get()
					console.log(res)
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: `删除失败，错误信息为：${err.message}`,
						showCancel: false
					})
					console.error(err)
				})
			},
			update() {
				
				
				console.log(this.editem);
					
				
		
					
				let data={
					product:this.editem.product,
					count:this.editem.count,
					total:this.editem.price*this.editem.count,
					price:this.editem.price*1,
					id:this.editem._id,
					openid:this.editem.openid,
					show:false,
					showdetails:false
				}
			
			  console.log(data)
			
				uni.showLoading({
					title: '处理中...'
				})
				
				if (this.editem.product == "") {
					this.$refs.uToast.show({
						title: '请输入商品名称',
						type: 'warning',
					})
					return
				} else if (this.editem.price <= 0 || this.editem.price == '') {
					this.$refs.uToast.show({
						title: '请输入单价',
						type: 'warning',
					})
					return
				} else if (this.editem.count <= 0) {
					this.$refs.uToast.show({
						title: '请输入数量',
						type: 'warning',
					})
					return
				}
				
				



				uniCloud.callFunction({
					name: 'update',
					data: data
				}).then((res) => {
					uni.hideLoading()

					this.get()
					console.log(res)
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: `更新操作执行失败，错误信息为：${err.message}`,
						showCancel: false
					})
					console.error(err)
				})
			},
			// 获取
			get() {
				this.reset()
				uni.showLoading({
					title: '处理中...'
				})
				uniCloud.callFunction({
					data: {
						openid: this.$store.state.vuex_openid
					},
					name: 'get'
				}).then((res) => {
					uni.hideLoading()

					console.log(res.result.data)
					this.list = res.result.data
					this.count = 0
					this.total = 0
					this.list.forEach((ele, index, arr) => {
						this.count += ele.count * 1
						this.total += ele.total * 1
					})


				}).catch((err) => {
					uni.hideLoading()

					console.error(err)
				})
			},
			upload() {
				new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						success: res => {
							const path = res.tempFilePaths[0]
							let ext
							// #ifdef H5
							ext = res.tempFiles[0].name.split('.').pop()
							const options = {
								filePath: path,
								cloudPath: Date.now() + '.' + ext
							}
							resolve(options)
							// #endif
							// #ifndef H5
							uni.getImageInfo({
								src: path,
								success(info) {
									const options = {
										filePath: path,
										cloudPath: Date.now() + '.' + info.type.toLowerCase()
									}
									resolve(options)
								},
								fail(err) {
									reject(new Error(err.errMsg || '未能获取图片类型'))
								}
							})
							// #endif
						},
						fail: () => {
							reject(new Error('Fail_Cancel'))
						}
					})
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
						}
					})
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					uni.showModal({
						content: '图片上传成功，fileId为：' + res.fileID,
						showCancel: false
					})
				}).catch((err) => {
					uni.hideLoading()
					console.log(err);
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败，错误信息为：${err.message}`,
							showCancel: false
						})
					}
				})
			}
		}
	}
</script>

<style scoped lang="less">
	.content {

		.form {
			.form-item {
				padding: 10rpx 10rpx;
				border-bottom: 1px solid #f6f7f9;

				.inputbox {
					padding-top: 10rpx;

					.labeltext {
						width: 120rpx;
						display: inline-block;
					}

					.inputstyle {
						width: 350rpx;
						border: 1rpx solid #C0C0C0;
						border-radius: 15rpx;
						padding: 0rpx 10rpx;
						font-size: 25rpx;
					}
				}

				.moneybox {
					position: relative;
					top: 0rpx
				}

				.money {
					display: inline-block;
					line-height: 45rpx;
					width: 150rpx;
					word-wrap: break-word;
					text-align: right;
				}

				/deep/ .u-numberbox {
					position: relative;
					top: 5rpx;
					font-size: 25rpx !important;

					.u-icon-minus {
						font-size: 20rpx !important;
						height: 30rpx !important;
						width: 50rpx;

					}

					.u-number-input {
						font-size: 20rpx !important;
						height: 20rpx !important;
						width: 100rpx !important;
						line-height: 20rpx !important;
						border-radius: 10rpx;
					}

					.u-icon-plus {
						font-size: 20rpx !important;
						height: 30rpx !important;
						width: 50rpx;
					}


				}
			}

		}
	}

	.table {
		font-size: 25rpx;
		// border: 1px solid #2d72f5;
		// box-shadow: 5rpx 5rpx 2rpx #2d72f5;
		padding: 10rpx 20rpx;
		margin: 0rpx 10rpx;
		border-radius: 10rpx;
		// color:#FFFFFF;
		// /deep/ .u-swipe-del{
		// 	width: 100rpx !important;
		// }
	}

	.table-item {
		padding: 0rpx 10rpx;
		border-bottom: 1px solid #F3F7FA;
		padding-bottom: 10rpx 0rpx;

		.showdetails {
			padding: 10rpx 0rpx;
		}
	}

	.itemhear {
		padding: 10rpx 0rpx;

		.icon {
			color: #2d72f5;
			position: relative;
			top: 5rpx;
			left: 5rpx;
		}
	}

	.iconbottom {
		transform: rotate(90deg) translateY(5rpx) translateX(-5rpx);
		// -ms-transform: rotate(90deg)  translateY(5px);;
		// /* IE 9 */
		// -moz-transform: rotate(90deg)  translateY(5px);;
		// /* Firefox */
		// -webkit-transform: rotate(90deg)  translateY(5px);;
		// /* Safari 和 Chrome */
		// -o-transform: rotate(90deg)  translateY(5px);;

	}

	.slide-fade-enter-active {
		transition: all 2s ease;
	}

	.slide-fade-leave-active {
		transition: all .5s cubic-bezier(1.0, 0.5, 0.8, 1.0);
	}

	.slide-fade-enter,
	.slide-fade-leave-to

	/* .slide-fade-leave-active 用于 2.1.8 以下版本 */
		{
		transform: translateY(-10px);
		opacity: 0;
	}

	.fleexbottom {
		position: fixed;
		bottom: 0rpx;
		width: 750rpx;

		box-sizing: border-box;
		background-color: #FFFFFF;
		padding-bottom: 10rpx;
	}

	.ddbutton {
		color: #FFFFFF;
		background-color: #2d72f5;
		border-radius: 10rpx;
		padding: 5rpx 20rpx;
		font-size: 30rpx;
	}

	.u-number-box {
		width: 230rpx;
		position: relative;
		top: 5rpx;

		input {
			width: 100rpx;
			border: 1px solid #C0C0C0;
			border-radius: 10rpx;
			font-size: 25rpx;
			position: relative;
			top: 5rpx;
		}
	}

	.topre {
		position: relative;
		top: 10rpx;
	}
</style>
